import path from 'path';

import {
    EnvironmentParameters,
    EnvironmentType,
    getEnvironmentValue,
    AppSettings,
} from '../environment';
import { getConfig } from './utils';

export class ConfigCenterServerSide {
    private readonly env: EnvironmentType;

    private readonly rootPath: string;

    private readonly configPath: string;

    private readonly appSettings: AppSettings;

    constructor() {
        this.env =
            getEnvironmentValue(EnvironmentParameters.RUN_ENV) === EnvironmentType.prd
                ? EnvironmentType.prd
                : EnvironmentType.dev;
        this.rootPath = getEnvironmentValue(EnvironmentParameters.ROOT_PATH) || '';
        this.configPath = path.join(this.rootPath, './conf');

        // appSettings (only load local config)
        this.appSettings = getConfig<AppSettings>('app-settings.json', this.configPath, this.env);
    }

    public getAppSettings(): AppSettings {
        return this.appSettings;
    }

    public getConfig<T = any>(name: string): T {
        const trimName = name?.toString()?.trim();

        return getConfig(
            `${trimName}${trimName?.endsWith('.json') ? '' : '.json'}`,
            this.configPath,
            this.env,
        );
    }
}
